package com.example.a2022application.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.a2022application.BaseActivity;
import com.example.a2022application.R;
import com.example.a2022application.bean.TaskBean;
import com.example.a2022application.bean.TeacherBean;
import com.example.a2022application.bean.UploadBean;
import com.example.a2022application.net.Urls;
import com.example.a2022application.utils.SpUtils;
import com.example.a2022application.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import androidx.annotation.Nullable;

/**
 * 查看作业
 */
public class ViewJobActivity extends BaseActivity {
    private String tid;
    private ListView listtask;
    ShowListAdapter adapter;
    List<TaskBean.DataBean> tList= new ArrayList();
    private static int REQUEST_CODE_DOC = 1;
    private String endtime;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_viewjob);
        listtask = findViewById(R.id.listtask);
        Intent intent = getIntent();
        tid = intent.getStringExtra("oid");
        initData();
    }

    private void initData() {
        OkGo.<String>post(Urls.SELECTTASK)
                .params("timetable_id",tid)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        TaskBean bean = getGson().fromJson(response.body(),TaskBean.class);
                        if (bean.getCode() == 0){
                            if (bean.getData().size()>0){
                                tList = bean.getData();
                                adapter = new ShowListAdapter();
                                listtask.setAdapter(adapter);
                                listtask.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                        TaskBean.DataBean task = (TaskBean.DataBean) tList.get(i);
                                        new AlertDialog.Builder(ViewJobActivity.this)
                                                .setTitle("下载该作业吗？")
                                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialogInterface, int i) {
                                                        downTask(task.getFilename());
                                                    }

                                                })
                                                .setNegativeButton("取消", null)
                                                .show();
                                    }
                                });
                            }
                        }

                    }
                });

    }

    private void downTask(String filename) {
        OkGo.<File>post(Urls.DOWNLOAD)
                .params("fileName",filename)
                .execute(new FileCallback() {
                    @Override
                    public void onSuccess(Response<File> response) {
                        File body = response.body();
                        Log.e("tag","body---"+body);
                        if (body.exists()){
                            ToastUtil.showToast("文件下载成功");
                        }
                    }

                    @Override
                    public void downloadProgress(Progress progress) {
                        float fraction = progress.fraction;  //0-1 之间的一个数
//                        bar.setProgress((int) (fraction*100));//用于进度条
                        System.out.println("===================="+fraction);

                        super.downloadProgress(progress);
                    }
                });

    }

    public class ShowListAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return tList.size();
        }

        @Override
        public Object getItem(int i) {
            return tList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ShowListAdapter.ViewHolder viewHolder;
            //判断界面是否有缓存
            if(convertView == null){
                viewHolder= new ShowListAdapter.ViewHolder();
                convertView= LinearLayout.inflate(parent.getContext(), R.layout.item_task, null);

                viewHolder.tv_task = convertView.findViewById(R.id.tv_task);
                viewHolder.tv_endtime = convertView.findViewById(R.id.tv_endtime);
                viewHolder.tv_send = convertView.findViewById(R.id.tv_send);

                convertView.setTag(viewHolder);
            }else{
                viewHolder=(ShowListAdapter.ViewHolder)convertView.getTag();
            }
            TaskBean.DataBean teacher = (TaskBean.DataBean) tList.get(position);

            viewHolder.tv_task.setText(teacher.getOrigname());
            viewHolder.tv_endtime.setText(teacher.getEndtime());
            viewHolder.tv_send.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Calendar c = Calendar.getInstance();
                    String date = sdf.format(c.getTime());
                    boolean ctime = compareDate(date,teacher.getEndtime());
                    if (ctime){
                        getDocument();
                        endtime = teacher.getEndtime();
                    }else {
                        ToastUtil.showToast("已过截止时间");
                    }
                }
            });

            return convertView;
        }

        private class ViewHolder{
            TextView tv_task;
            TextView tv_endtime;
            TextView tv_send;
        }
    }

    public boolean compareDate(String nowDate, String compareDate) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date now = df.parse(nowDate);
            Date compare = df.parse(compareDate);
            if (now.before(compare)) {
                return true;
            } else {
                return false;
            }
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
    }
    private void getDocument() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("application/msword,application/pdf");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        // Only the system receives the ACTION_OPEN_DOCUMENT, so no need to test.
        startActivityForResult(intent, REQUEST_CODE_DOC);
    }

    @Override
    protected void onActivityResult(int req, int result, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(req, result, data);
        Log.e("tag","result--"+result);
        if (result == RESULT_OK)
        {
            Uri fileuri = data.getData();
            String docFilePath = getFileNameByUri(this, fileuri);
            File file = new File(docFilePath);

            Log.e("tag","file----"+file.exists());
            List<File> files = new ArrayList();
            files.add(file);
            String student_id = SpUtils.getString(ViewJobActivity.this,"userid");
            OkGo.<String>post(Urls.UPLOADSTUDENT)
                    .isMultipart(true)
                    .params("endtime",endtime)
                    .params("timetable_id",tid)
                    .params("student_id",student_id)
                    .addFileParams("file", files)
                    .execute(new StringCallback() {

                        @SuppressLint("LongLogTag")
                        @Override
                        public void onSuccess(Response<String> response) {
                            Log.e("TAG", "文件上传---- " + response.body());
                            try {
                                UploadBean bean = getGson().fromJson(response.body(), UploadBean.class);
                                if (bean.getCode() == 0){
                                    finish();
                                }

                                ToastUtil.showToast(bean.getMessage());
                            } catch (Exception e) {

                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            Log.e("TAG", "onError---- " + response.message());
                        }
                    });
        }
    }
    private String getFileNameByUri(Context context, Uri uri)
    {
        String filepath = "";//default fileName
        //Uri filePathUri = uri;
        File file;
        if (uri.getScheme().toString().compareTo("content") == 0)
        {
            Cursor cursor = context.getContentResolver().query(uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA, MediaStore.Images.Media.ORIENTATION }, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

            cursor.moveToFirst();

            String mImagePath = cursor.getString(column_index);
            cursor.close();
            filepath = mImagePath;

        }
        else if (uri.getScheme().compareTo("file") == 0)
        {
            try
            {
                file = new File(new URI(uri.toString()));
                if (file.exists())
                    filepath = file.getAbsolutePath();

            }
            catch (URISyntaxException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        else
        {
            filepath = uri.getPath();
        }
        return filepath;
    }
}
